package com.hmdp.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Slf4j
@Component
//利用redis实现全局id生成器（格式：符号位（1bit）+时间戳(31bit)+序列号(32bit)）
public class RedisIdWorker {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    //起始时间戳
    private final static Long START_TIME = 1735689600L;
    private final static int COUNT_BITS = 32;
    public long nextId(String keyPrefix){
        //1.生成时间戳
//        LocalDateTime time = LocalDateTime.of(2025, 1, 1, 0, 0, 0);
//        long second = time.toEpochSecond(ZoneOffset.UTC);
//        log.info("second: {}", second);
        long now = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC);
        log.info("now: {}", now);
        //获取当前时间戳
        long timeStamp = now - START_TIME;

        //2.生成序列号
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        long count = stringRedisTemplate.opsForValue().increment("icr" + keyPrefix + ":" + date);
        //拼接并返回
        return timeStamp << COUNT_BITS | count;
    }

}
